package com.idanchuang.component.config.apollo;

import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.idanchuang.component.config.apollo.config.ApolloConfigBean;
import com.idanchuang.component.config.apollo.support.DefaultRefreshFailedEvent;
import com.idanchuang.component.config.apollo.support.RefreshFailedEvent;
import com.idanchuang.component.config.apollo.util.SpringContextUtil;
import com.idanchuang.spi.config.IConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author yjy
 * @date 2019/11/8 11:12
 **/
@Configuration
@EnableApolloConfig
@ConditionalOnProperty(prefix = "apollo.bootstrap", name = "enabled", havingValue = "true", matchIfMissing = true)
public class ComponentConfigApolloAutoConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "apollo.bootstrap")
    public ApolloConfigBean apolloConfigBean() {
        return new ApolloConfigBean();
    }

    @Bean("dcComponentConfigApolloSpringContextUtil")
    @ConditionalOnMissingBean(name = "dcComponentConfigApolloSpringContextUtil")
    public SpringContextUtil springContextUtil() {
        return new SpringContextUtil();
    }

    @Bean("componentApolloConfigService")
    @ConditionalOnMissingBean(IConfig.class)
    public ConfigService configService(ApolloConfigBean apolloConfigBean) {
        return new ConfigService(apolloConfigBean);
    }

    @Bean
    @ConditionalOnMissingBean(RefreshFailedEvent.class)
    public DefaultRefreshFailedEvent simpleRefreshFailedEvent() {
        return new DefaultRefreshFailedEvent();
    }

    @Bean("componentConfigApolloBeforeRunner")
    @ConditionalOnMissingBean(name = "componentConfigApolloBeforeRunner")
    public BeforeRunner beforeRunner(IConfig iConfig, RefreshScope refreshScope) {
        return new BeforeRunner(iConfig, refreshScope);
    }

}
